//
// Created by liuml on 2018/10/22.
//

#include "XYQueue.h"

XYQueue::XYQueue(XYPlayStatus *playStatus) {
    this->playStatus = playStatus;
    pthread_mutex_init(&mutexPacket, NULL);

    pthread_cond_init(&condPacket, NULL);
}

XYQueue::~XYQueue() {
    clearAvpacket();
    pthread_mutex_destroy(&mutexPacket);
    pthread_cond_destroy(&condPacket);

}

int XYQueue::putAvpacket(AVPacket *packet) {
    pthread_mutex_lock(&mutexPacket);

    queuePacket.push(packet);
//    LOGD("入队 放入一个AVPacket到队列里面,个数为%d", queuePacket.size())
    pthread_cond_signal(&condPacket);

    pthread_mutex_unlock(&mutexPacket);
    return 0;
}

int XYQueue::getAvpacket(AVPacket *packet) {

    pthread_mutex_lock(&mutexPacket);

    while (playStatus != NULL && !playStatus->exit) {
        if (queuePacket.size() > 0) {
            //front 是队头
            AVPacket *avPacket = queuePacket.front();
            //拷贝
            if (av_packet_ref(packet, avPacket) == 0) {
                queuePacket.pop();
            }
            //拷贝完之后释放 二次释放
            av_packet_free(&avPacket);
            av_free(avPacket);
            avPacket = NULL;
//            LOGD("出队 从队列里取出一个AVPacket,还剩下%d个", queuePacket.size());
            break;
        } else {
            pthread_cond_wait(&condPacket, &mutexPacket);
        }
    }

    pthread_mutex_unlock(&mutexPacket);
    return 0;
}

int XYQueue::getQueueSize() {
    int size = 0;
    pthread_mutex_lock(&mutexPacket);
    size = queuePacket.size();
    pthread_mutex_unlock(&mutexPacket);
    return size;
}

void XYQueue::clearAvpacket() {

    pthread_cond_signal(&condPacket);

    pthread_mutex_lock(&mutexPacket);

    while (!queuePacket.empty()) {
        AVPacket *packet = queuePacket.front();
        queuePacket.pop();
        av_packet_free(&packet);
        av_free(packet);
        packet = NULL;
    }


    pthread_mutex_unlock(&mutexPacket);

}

